<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/pace-js@1/themes/blue/pace-theme-minimal.css">
  <script src="//cdn.jsdelivr.net/npm/pace-js@1/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yimig.github.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="你捡起了道具：遗失的纸片2# 一张普通的纸片，隐隐约约能够看到目录：“强制类型转换、运算符、语句、对象、函数、作用域”。边角还有被撕扯的痕迹，它们应该属于一个笔记本，但不知为什么被主人撕下来丢掉了。 提示：集齐所有纸片应该可以得到一本技能书。 👇点击下方按钮调查">
<meta property="og:type" content="article">
<meta property="og:title" content="【JS】js学习小笔记 2#">
<meta property="og:url" content="http://yimig.github.io/2019/04/22/js_note2/index.html">
<meta property="og:site_name" content="Tim&#39;s Blog">
<meta property="og:description" content="你捡起了道具：遗失的纸片2# 一张普通的纸片，隐隐约约能够看到目录：“强制类型转换、运算符、语句、对象、函数、作用域”。边角还有被撕扯的痕迹，它们应该属于一个笔记本，但不知为什么被主人撕下来丢掉了。 提示：集齐所有纸片应该可以得到一本技能书。 👇点击下方按钮调查">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-04-22T09:45:02.000Z">
<meta property="article:modified_time" content="2021-01-15T02:34:22.144Z">
<meta property="article:author" content="Tim">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="js学习笔记">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yimig.github.io/2019/04/22/js_note2/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【JS】js学习小笔记 2# | Tim's Blog</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64126ab668fa908027cba9464a0afec7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Tim's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Learn Everything!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-schedule">

    <a href="/schedule/" rel="section"><i class="fa fa-fw fa-calendar"></i>日程表</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/yimig" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yimig.github.io/2019/04/22/js_note2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/avatar.png">
      <meta itemprop="name" content="Tim">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tim's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【JS】js学习小笔记 2#
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-04-22 17:45:02" itemprop="dateCreated datePublished" datetime="2019-04-22T17:45:02+08:00">2019-04-22</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-01-15 10:34:22" itemprop="dateModified" datetime="2021-01-15T10:34:22+08:00">2021-01-15</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Coding/" itemprop="url" rel="index"><span itemprop="name">Coding</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Coding/Web/" itemprop="url" rel="index"><span itemprop="name">Web</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Coding/Web/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Coding/Web/JavaScript/Common/" itemprop="url" rel="index"><span itemprop="name">Common</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              <span>3.4k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              <span>3 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>你捡起了道具：<strong>遗失的纸片2#</strong> 一张普通的纸片，隐隐约约能够看到目录：“<strong>强制类型转换、运算符、语句、对象、函数、作用域</strong>”。边角还有被撕扯的痕迹，它们应该属于一个笔记本，但不知为什么被主人撕下来丢掉了。 提示：集齐所有纸片应该可以得到一本技能书。 👇点击下方按钮调查<br><a id="more"></a></p>
<h2 id="7-强制类型转换"><a href="#7-强制类型转换" class="headerlink" title="7.强制类型转换"></a>7.强制类型转换</h2><h3 id="转string"><a href="#转string" class="headerlink" title="转string:"></a>转<code>string</code>:</h3><ol>
<li><strong>直接调用被转换对象的<code>toString()</code>方法</strong>，该方法不会影响原值，会将转换后的结果返回。<strong><code>null</code>与<code>undefined</code>无<code>toString()</code>方法。</strong></li>
<li><strong>调用<code>String()</code>函数</strong>，并将被转换的变量作为参数传入，<strong>使用<code>String()</code>函数转换时，<code>null</code>→”null”,<code>undefined</code>→”undefined”。</strong></li>
</ol>
<h3 id="转Number"><a href="#转Number" class="headerlink" title="转Number:"></a>转<code>Number</code>:</h3><ol>
<li>使用<code>Number()</code>函数</li>
</ol>
<div class="table-container">
<table>
<thead>
<tr>
<th>？→数值</th>
<th>转换结果</th>
</tr>
</thead>
<tbody>
<tr>
<td>字符串</td>
<td>非纯数字转换为<code>NaN</code>，空值/空格转换为0</td>
</tr>
<tr>
<td>布尔</td>
<td>true→1，false→0</td>
</tr>
<tr>
<td>null</td>
<td>0</td>
</tr>
<tr>
<td>undefined</td>
<td><code>NaN</code></td>
</tr>
</tbody>
</table>
</div>
<p>2.使用<code>parseInt()</code>/<code>parseFloat()</code>将字符串转换为整型/浮点型 <strong>该方法可去除字符串中非数字部分</strong> <strong>原理：读到第一个非数字位，往后都忽略</strong></p>
<blockquote>
<p>“123px”→123 “123px456”→123”123.5”→123</p>
</blockquote>
<p><strong>如果对非String使用<code>parseInt()</code>/<code>parseFloat()</code>，会先转为<code>String</code>，再转为<code>Number</code>，如</strong></p>
<blockquote>
<p>true→”true”→NaN 123.5→”123.5”→123 所以<code>parseInt()</code>也有取整的作用</p>
</blockquote>
<p>3.其他进制数字</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>进制</th>
<th>命名规定</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hex</td>
<td>0x??</td>
</tr>
<tr>
<td>Oct</td>
<td>0??</td>
</tr>
<tr>
<td>Bin</td>
<td>0B??</td>
</tr>
</tbody>
</table>
</div>
<p>像“070”这种字符串有的浏览器会当成八进制解析</p>
<blockquote>
<p>明确制定进制：parseInt(a,10)可向<code>parseInt()</code>传两个参数，第二个参数表示进制。</p>
</blockquote>
<h3 id="转Boolean"><a href="#转Boolean" class="headerlink" title="转Boolean:"></a>转<code>Boolean</code>:</h3><p>使用<code>Boolean()</code>参数：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>？→Boolean</th>
<th>转换结果</th>
</tr>
</thead>
<tbody>
<tr>
<td>数字</td>
<td>除了0和<code>NaN</code>，其他都是true</td>
</tr>
<tr>
<td>字符串</td>
<td>除了空串，其他都是true</td>
</tr>
<tr>
<td>对象</td>
<td>true</td>
</tr>
<tr>
<td>null/undefined</td>
<td>false</td>
</tr>
</tbody>
</table>
</div>
<h3 id="unicode转换："><a href="#unicode转换：" class="headerlink" title="unicode转换："></a>unicode转换：</h3><ol>
<li>JS：<strong>\\u+unicode(四位16进制编码)</strong></li>
<li>HTML：<strong>&amp;#+unicode(十进制编码)</strong></li>
</ol>
<h2 id="8-运算符"><a href="#8-运算符" class="headerlink" title="8.运算符"></a>8.运算符</h2><div class="table-container">
<table>
<thead>
<tr>
<th>运算符</th>
<th>运算法则</th>
<th>隐式转换</th>
</tr>
</thead>
<tbody>
<tr>
<td>+</td>
<td>①NaN与任何数运算都得NaN②亦可字符串合并③任何值与字符串相加都转为字符串合并</td>
<td>是</td>
</tr>
<tr>
<td>-、*、/……</td>
<td>任何值都转换为Number参与运算</td>
<td>是</td>
</tr>
<tr>
<td>+(正)、-(负)</td>
<td>非Number值先转为Number，再求正/反</td>
<td>是</td>
</tr>
<tr>
<td>!、\</td>
<td>\</td>
<td>、&amp;&amp;</td>
<td>先转为布尔值，再进行逻辑运算，且返回原值，而不是bool变量</td>
<td>是</td>
</tr>
<tr>
<td>-</td>
<td>与：第一个为true，则必然返回第二个；第一个为false，则必然返回第一个（找false）</td>
</tr>
<tr>
<td>-</td>
<td>或：第一个为true，则必然返回第一个，第一个为false，则必然返回第二个（找true）</td>
</tr>
<tr>
<td>>/\\&lt;</td>
<td>①非数值比较时将其转换为数值②任何值与NaN比较都是false③如果富豪两侧都是字符串，则不会</td>
<td>成数字而是转成相应的字符，使用unicode编码（一位一位比，两位一样就比下一位，直至比出</td>
<td>果）→比较字符串时一定要转型</td>
<td>是</td>
</tr>
<tr>
<td>\==/!=</td>
<td>①undefined衍生自null，所以相等②NaN不与任何值相等，包括它本身③判断是否为NaN：`isNaN(</td>
<td>`函数</td>
<td>是</td>
</tr>
<tr>
<td>\===</td>
<td>全等→不做类型转换，类型不同的直接返回false</td>
<td>否</td>
<td>!==</td>
<td>不全等→不做类型转换，类型相同直接返回false</td>
<td>否</td>
</tr>
</tbody>
</table>
</div>
<h2 id="9-语句"><a href="#9-语句" class="headerlink" title="9.语句"></a>9.语句</h2><p>自上向下执行，可用{}对其分组。 同一个{}称一组语句，要么都执行要么都不执行，一个{}称代码块，{}只有分组作用，不能隔离语句</p>
<h3 id="流程控制"><a href="#流程控制" class="headerlink" title="流程控制"></a>流程控制</h3><div class="table-container">
<table>
<thead>
<tr>
<th>语句</th>
<th>语法</th>
<th>注释</th>
</tr>
</thead>
<tbody>
<tr>
<td>条件</td>
<td>if(?){A}else{B}</td>
<td>-</td>
</tr>
<tr>
<td>条件分支</td>
<td>switch(?){case 表达式：语句 break;……..default:语句}</td>
<td>case后是<strong>全等判断</strong></td>
</tr>
<tr>
<td>循环</td>
<td>while(条件表达式){语句}/for(初始化表达式;条件表达式;更新表达式){}</td>
<td>每次循环前先对条件表达式进行判断，<strong>若为true</strong>则进入循环体</td>
</tr>
</tbody>
</table>
</div>
<h2 id="10-对象"><a href="#10-对象" class="headerlink" title="10.对象"></a>10.对象</h2><h3 id="分类"><a href="#分类" class="headerlink" title="分类"></a>分类</h3><ul>
<li>内建对象：<strong>由ES标准中定义的对象</strong>，在任何ES实现中都可使用（Math、String等）</li>
<li>宿主对象：<strong>由JS运行环境提供的对象</strong>，目前来讲指浏览器提供的对象，如BOM、DOM</li>
<li>自定义对象：<strong>开发者自己创建的对象</strong></li>
</ul>
<h3 id="创建对象"><a href="#创建对象" class="headerlink" title="创建对象"></a>创建对象</h3><h4 id="方法一：声明后设置属性"><a href="#方法一：声明后设置属性" class="headerlink" title="方法一：声明后设置属性"></a>方法一：声明后设置属性</h4><p>step1.实例化对象：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj=<span class="keyword">new</span> <span class="built_in">Object</span>();</span><br></pre></td></tr></table></figure>
<p>step2.在对象中添加属性&amp;方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">obj.name=<span class="string">&quot;张三&quot;</span>;</span><br><span class="line">obj.gender=<span class="string">&quot;男&quot;</span>;</span><br><span class="line">obj.age=<span class="number">18</span>;</span><br><span class="line">obj.fun=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br></pre></td></tr></table></figure>
<p>step3.读取属性：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(obj.name);</span><br></pre></td></tr></table></figure>
<p><strong>如果读取对象中未定义的属性，不会报错，返回undefined</strong></p>
<h4 id="方法二：声明时设置属性"><a href="#方法二：声明时设置属性" class="headerlink" title="方法二：声明时设置属性"></a>方法二：声明时设置属性</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj=&#123;</span><br><span class="line">    name:<span class="string">&quot;张三&quot;</span>,</span><br><span class="line">    gender:<span class="string">&quot;男&quot;</span>,</span><br><span class="line">    age:<span class="number">18</span>,</span><br><span class="line">    fun:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用该方法声明对象时<strong>属性名</strong>的引号可加可不加，但使用特殊名时必须加。 属性与值之间使用“:”链接，各属性用“,”连接，结尾属性不加“,”。</p>
<h3 id="属性名-值"><a href="#属性名-值" class="headerlink" title="属性名/值"></a>属性名/值</h3><p>属性名：对象的属性名不强制使用命名规范，但若使用不符合命名规范的名称，调用属性时应使用<code>对象[属性名]</code>的方法，此处obj[name]=obj.name,但特殊命名无法使用点调用。<strong>中括号里也可以传入变量</strong> 属性值:可以是任意值，包括对象。</p>
<h3 id="in运算符"><a href="#in运算符" class="headerlink" title="in运算符"></a>in运算符</h3><p>检查一个对象中有无规定属性，如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(<span class="string">&quot;test&quot;</span> <span class="keyword">in</span> obj)</span><br></pre></td></tr></table></figure>
<p>→检查obj对象中有无“test”属性</p>
<h2 id="11-函数"><a href="#11-函数" class="headerlink" title="11.函数"></a>11.函数</h2><blockquote>
<p>函数也是一个对象</p>
</blockquote>
<h3 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h3><h4 id="方法一：声明函数对象（不常用）"><a href="#方法一：声明函数对象（不常用）" class="headerlink" title="方法一：声明函数对象（不常用）"></a>方法一：声明函数对象（不常用）</h4><p>step1.创建一个函数对象，可以将要封装的代码以字符串的形式传递给构造函数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fun=<span class="keyword">new</span> <span class="built_in">Function</span>(<span class="string">&quot;console.log(&#x27;Hello&#x27;);&quot;</span>);</span><br></pre></td></tr></table></figure>
<p>step2.调用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fun();</span><br></pre></td></tr></table></figure>
<h4 id="方法二：使用函数声明创建函数"><a href="#方法二：使用函数声明创建函数" class="headerlink" title="方法二：使用函数声明创建函数"></a>方法二：使用函数声明创建函数</h4><blockquote>
<p>function 函数名([形参1,形参2….]) { 语句… }</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fun</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Hello&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="方法三：使用函数表达式创建函数"><a href="#方法三：使用函数表达式创建函数" class="headerlink" title="方法三：使用函数表达式创建函数"></a>方法三：使用函数表达式创建函数</h4><blockquote>
<p>var 函数名=function([形参1,形参2….]) { 语句… }</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fun=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Hello&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h3><p>函数不会检查参数的数量，<strong>未赋值的形参将初始化为undefined</strong></p>
<h3 id="返回值"><a href="#返回值" class="headerlink" title="返回值"></a>返回值</h3><p>使用<code>return</code>设置返回值，return后的语句不会执行。 <strong><code>return</code>后不接任何值，或者没有<code>return</code>语句函数将返回undefined</strong></p>
<h3 id="执行匿名函数（立即执行）"><a href="#执行匿名函数（立即执行）" class="headerlink" title="执行匿名函数（立即执行）"></a>执行匿名函数（立即执行）</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    alert(<span class="string">&quot;我是匿名函数&quot;</span>);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>
<p>第一个括号代表函数是一整个对象，后面括号将其执行→<strong>对象()</strong></p>
<h3 id="for…in语句"><a href="#for…in语句" class="headerlink" title="for…in语句"></a>for…in语句</h3><p>与for联用，与C#相似。 打印obj对象中所有的属性名与属性值：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printObject</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> n <span class="keyword">in</span> obj)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(n+<span class="string">&quot;:&quot;</span>+obj[n]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="12-作用域"><a href="#12-作用域" class="headerlink" title="12.作用域"></a>12.作用域</h2><blockquote>
<p>指一个变量的作用范围</p>
</blockquote>
<p>在JS中，有两种作用域：<strong>①全局作用域②函数作用域</strong></p>
<h3 id="①全局作用域"><a href="#①全局作用域" class="headerlink" title="①全局作用域"></a>①全局作用域</h3><p>创建方法：<strong>直接写在<code>script</code>标签下</strong> 生命周期：在页面打开时创建，页面关闭时销毁 调用方法：全局作用域中有个全局对象<code>window</code>可使用，其由浏览器创建。在全局作用域中创建的变量都会作为<code>window</code>的属性保存，创建的函数都会作为<code>window</code>的方法保存。</p>
<h4 id="变量的声明提前："><a href="#变量的声明提前：" class="headerlink" title="变量的声明提前："></a>变量的声明提前：</h4><p><code>var</code>声明的变量会在所有代码执行之前被声明，<strong>但不会被赋值</strong></p>
<h4 id="函数的声明提前："><a href="#函数的声明提前：" class="headerlink" title="函数的声明提前："></a>函数的声明提前：</h4><ul>
<li>使用函数声明形式创建的函数（<code>function 函数() &#123;&#125;</code>）<strong>会在所有代码执行之前就被创建，所以我们可以在创建声明前来调用</strong></li>
<li>使用函数表达式（<code>var fun=function()&#123;&#125;</code>）创建的函数不会被提前创建，<strong>不能提前调用</strong></li>
</ul>
<h3 id="②函数作用域"><a href="#②函数作用域" class="headerlink" title="②函数作用域"></a>②函数作用域</h3><p>生命周期：调用函数时创建函数作用域，函数执行完毕后作用域销毁 <strong>多函数作用域相互独立，函数作用域可访问全局作用域</strong> 函数操作变量时，先在自己作用域中找，找不到再去上一级作用域中找。<strong>若要直接使用全局作用域可以通过window对象的属性调用</strong></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/javascript/" rel="tag"># javascript</a>
              <a href="/tags/js%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># js学习笔记</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/04/21/js_note1/" rel="prev" title="【JS】js学习小笔记 1#">
      <i class="fa fa-chevron-left"></i> 【JS】js学习小笔记 1#
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/04/27/regex_entry/" rel="next" title="【Regex】正则表达式语法">
      【Regex】正则表达式语法 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E5%BC%BA%E5%88%B6%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2"><span class="nav-number">1.</span> <span class="nav-text">7.强制类型转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BD%ACstring"><span class="nav-number">1.1.</span> <span class="nav-text">转string:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BD%ACNumber"><span class="nav-number">1.2.</span> <span class="nav-text">转Number:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BD%ACBoolean"><span class="nav-number">1.3.</span> <span class="nav-text">转Boolean:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#unicode%E8%BD%AC%E6%8D%A2%EF%BC%9A"><span class="nav-number">1.4.</span> <span class="nav-text">unicode转换：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="nav-number">2.</span> <span class="nav-text">8.运算符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-%E8%AF%AD%E5%8F%A5"><span class="nav-number">3.</span> <span class="nav-text">9.语句</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6"><span class="nav-number">3.1.</span> <span class="nav-text">流程控制</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-%E5%AF%B9%E8%B1%A1"><span class="nav-number">4.</span> <span class="nav-text">10.对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%86%E7%B1%BB"><span class="nav-number">4.1.</span> <span class="nav-text">分类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E5%AF%B9%E8%B1%A1"><span class="nav-number">4.2.</span> <span class="nav-text">创建对象</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E4%B8%80%EF%BC%9A%E5%A3%B0%E6%98%8E%E5%90%8E%E8%AE%BE%E7%BD%AE%E5%B1%9E%E6%80%A7"><span class="nav-number">4.2.1.</span> <span class="nav-text">方法一：声明后设置属性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E4%BA%8C%EF%BC%9A%E5%A3%B0%E6%98%8E%E6%97%B6%E8%AE%BE%E7%BD%AE%E5%B1%9E%E6%80%A7"><span class="nav-number">4.2.2.</span> <span class="nav-text">方法二：声明时设置属性</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B1%9E%E6%80%A7%E5%90%8D-%E5%80%BC"><span class="nav-number">4.3.</span> <span class="nav-text">属性名&#x2F;值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#in%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="nav-number">4.4.</span> <span class="nav-text">in运算符</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-%E5%87%BD%E6%95%B0"><span class="nav-number">5.</span> <span class="nav-text">11.函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA"><span class="nav-number">5.1.</span> <span class="nav-text">创建</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E4%B8%80%EF%BC%9A%E5%A3%B0%E6%98%8E%E5%87%BD%E6%95%B0%E5%AF%B9%E8%B1%A1%EF%BC%88%E4%B8%8D%E5%B8%B8%E7%94%A8%EF%BC%89"><span class="nav-number">5.1.1.</span> <span class="nav-text">方法一：声明函数对象（不常用）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E4%BA%8C%EF%BC%9A%E4%BD%BF%E7%94%A8%E5%87%BD%E6%95%B0%E5%A3%B0%E6%98%8E%E5%88%9B%E5%BB%BA%E5%87%BD%E6%95%B0"><span class="nav-number">5.1.2.</span> <span class="nav-text">方法二：使用函数声明创建函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B9%E6%B3%95%E4%B8%89%EF%BC%9A%E4%BD%BF%E7%94%A8%E5%87%BD%E6%95%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%88%9B%E5%BB%BA%E5%87%BD%E6%95%B0"><span class="nav-number">5.1.3.</span> <span class="nav-text">方法三：使用函数表达式创建函数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E6%95%B0"><span class="nav-number">5.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E5%80%BC"><span class="nav-number">5.3.</span> <span class="nav-text">返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%89%A7%E8%A1%8C%E5%8C%BF%E5%90%8D%E5%87%BD%E6%95%B0%EF%BC%88%E7%AB%8B%E5%8D%B3%E6%89%A7%E8%A1%8C%EF%BC%89"><span class="nav-number">5.4.</span> <span class="nav-text">执行匿名函数（立即执行）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#for%E2%80%A6in%E8%AF%AD%E5%8F%A5"><span class="nav-number">5.5.</span> <span class="nav-text">for…in语句</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">6.</span> <span class="nav-text">12.作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E2%91%A0%E5%85%A8%E5%B1%80%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">6.1.</span> <span class="nav-text">①全局作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%8F%98%E9%87%8F%E7%9A%84%E5%A3%B0%E6%98%8E%E6%8F%90%E5%89%8D%EF%BC%9A"><span class="nav-number">6.1.1.</span> <span class="nav-text">变量的声明提前：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E7%9A%84%E5%A3%B0%E6%98%8E%E6%8F%90%E5%89%8D%EF%BC%9A"><span class="nav-number">6.1.2.</span> <span class="nav-text">函数的声明提前：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E2%91%A1%E5%87%BD%E6%95%B0%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">6.2.</span> <span class="nav-text">②函数作用域</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Tim"
      src="/uploads/avatar.png">
  <p class="site-author-name" itemprop="name">Tim</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">90</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">40</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yimig" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yimig" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:zhangyiming@programmer.net" title="E-Mail → mailto:zhangyiming@programmer.net" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://leetcode.com/yimig/" title="LeeCode → https:&#x2F;&#x2F;leetcode.com&#x2F;yimig&#x2F;" rel="noopener" target="_blank"><i class="fa fa-fw fa-code"></i>LeeCode</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/tim-2-96" title="zhihu → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;tim-2-96" rel="noopener" target="_blank"><i class="fa fa-fw fa-question-circle"></i>zhihu</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://upane.cn/" title="https:&#x2F;&#x2F;upane.cn" rel="noopener" target="_blank">博客旧址</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tim</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">183k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:46</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_sphere.min.js"></script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : 'a876807f33858291f9d9',
      clientSecret: '7a5c6a83611c309965d7339d7ca5f16e34a21e9f',
      repo        : 'yimig.github.io',
      owner       : 'yimig',
      admin       : ['yimig'],
      id          : '3240654f47372df4971869f9a1b411d0',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

</body>
</html>
